<template>
    <div class="app">
        <main v-if="loading" class="loading">
            <div class="loader"></div>
        </main>
        <main v-else class="main">
            <div v-if="animationMessage" class="animation-message" :class="animationMessage.type">
                {{ animationMessage.text }}
            </div>
            <component v-if="metaData.bgm && !loading" :xRatio="xRatio" :yRatio="yRatio" :is="metaData.bgm.type" v-bind="metaData.bgm"/>
            <component v-if="metaData.script && !loading" :is="metaData.script.type" v-bind="metaData.script"/>
            <div ref="viewMain" class="wrap">
                <section v-for="(page, index) in metaData.pages" :key="index" class="page" :style="formatPageStyle(page.style)">
                    <component v-for="item in page.elements" :xRatio="xRatio" :yRatio="yRatio" :key="item.uid" :is="item.type" v-bind="item"/>
                </section>
            </div>
        </main>
    </div>
</template>

<script>
import Preloader from 'preloader'
import FullPage from '@/assets/js/fullpage'
import {DRAW_RECT_WIDTH, DRAW_RECT_HEIGHT, DEF_METADATA, IS_PROD, LOCAL_STORAGE_KEY} from '@/utils/constant'
import {formatPageStyle} from '@/utils/style'
import {ParseImgsFromPages} from '@/utils/images'

// 获取URL参数
function getQueryParam(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}

// 从localStorage获取指定flag的项目数据
function getProjectByFlag(flag) {
    try {
        const localData = JSON.parse(localStorage.getItem('local-projects') || '{"list":[],"count":0}');
        const project = localData.list.find(item => item.flag === flag);
        return project ? JSON.parse(project.content) : null;
    } catch (e) {
        return null;
    }
}

// 通过ID获取项目数据
async function getProjectById(id) {
    try {
        const basePath = window.location.origin + '/php';
        const response = await fetch(`${basePath}/hbsw-detail.php?id=${id}`);
        const result = await response.json();
        
        if (result.code === 0 && result.data) {
            return JSON.parse(result.data.content);
        } else {
            console.error('获取项目失败:', result.message);
            return null;
        }
    } catch (e) {
        console.error('获取项目数据失败:', e);
        return null;
    }
}

let initialMetaData = window.yee_metadata;
let loader = Preloader({xhrImages: false});

export default {
    data() {
        return {
            metaData: initialMetaData || DEF_METADATA,
            loading: true,
            progressRatio: 0,
            xRatio: window.innerWidth / DRAW_RECT_WIDTH,
            yRatio: window.innerHeight / DRAW_RECT_HEIGHT,
            animationMessage: null // 用于显示动画加载提示信息
        }
    },
    async created() {
        console.log('App created, initial metadata:', initialMetaData);
        // 检查URL中是否有flag参数
        const flag = getQueryParam('flag');
        // 检查URL中是否有id参数
        const id = getQueryParam('id');
        
        console.log('URL params - flag:', flag, 'id:', id);

        if (id) {
            // 根据ID从服务器获取项目数据
            const projectData = await getProjectById(id);
            if (projectData) {
                this.metaData = projectData;
            } else {
                // 如果找不到对应ID的项目，使用默认数据
                try {
                    this.metaData = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || DEF_METADATA;
                } catch (e) {
                    this.metaData = initialMetaData || DEF_METADATA;
                }
            }
        } else if (flag) {
            // 根据flag从localStorage中获取项目数据
            const projectData = getProjectByFlag(flag);
            if (projectData) {
                this.metaData = projectData;
            } else {
                // 如果找不到对应flag的项目，使用默认数据
                try {
                    this.metaData = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || DEF_METADATA;
                } catch (e) {
                    this.metaData = initialMetaData || DEF_METADATA;
                }
            }
        } else {
            // 没有flag或id参数，使用原来的逻辑
            if (IS_PROD) {
                // 在生产环境中也尝试从localStorage获取数据
                try {
                    this.metaData = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || DEF_METADATA;
                } catch (e) {
                    this.metaData = initialMetaData || DEF_METADATA;
                }
            } else {
                try {
                    this.metaData = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || DEF_METADATA;
                } catch (e) {
                    this.metaData = initialMetaData || DEF_METADATA;
                }
            }
        }
        
        console.log('Final metadata:', this.metaData);

        // 初始化图片加载器
        let imgs = ParseImgsFromPages(this.metaData.pages);
        console.log('Images to load:', imgs);
        
        // 如果没有图片需要加载，直接完成加载过程
        if (imgs.length === 0) {
            this.loading = false;
            this.$nextTick(this.initFullPage);
        } else {
            imgs.forEach(img => loader.addImage(img));
            loader.on('complete', this.onComplete);
            loader.load();
        }
    },
    methods: {
        formatPageStyle,
        onComplete() {
            console.log('Image loading complete');
            this.loading = false;
            this.$nextTick(this.initFullPage);
        },
        initFullPage() {
            console.log('Initializing full page');
            try {
                const fullPageInstance = new FullPage(this.$refs.viewMain, {
                    animationEnd() {}
                });
                
                // 显示动画加载成功提示
                this.showAnimationMessage('动画加载成功', 'success');
                
                // 初始化第一页的动画
                this.$nextTick(() => {
                    setTimeout(() => {
                        if (fullPageInstance && fullPageInstance.children && fullPageInstance.children[0]) {
                            console.log('Going to first page');
                            fullPageInstance._toPage(0);
                        }
                    }, 100);
                });
                
                // 添加定时器控制页面切换，确保动画按时间顺序执行
                // 30秒后切换到下一页（如果有的话）
                setTimeout(() => {
                    if (fullPageInstance && fullPageInstance.children && fullPageInstance.children[1]) {
                        console.log('Going to second page');
                        fullPageInstance.to(1);
                    }
                }, 30000);
            } catch (error) {
                // 显示动画加载失败提示
                console.error('动画加载失败:', error);
                this.showAnimationMessage('动画加载失败: ' + error.message, 'error');
            }
        },
        // 显示动画提示信息
        showAnimationMessage(text, type) {
            this.animationMessage = { text, type };
            // 3秒后自动隐藏提示
            setTimeout(() => {
                this.animationMessage = null;
            }, 3000);
        }
    }
}
</script>

<style lang="scss">
@import "../assets/scss/font";
@import "../assets/scss/common";

@keyframes spin {
  0% { 
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes spin-reverse {
  0% { 
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(-360deg);
  }
}

.app {
    flex: 1;
    .main, .wrap, .page {
        position: relative;
        height: 100%;
    }
    .loading {
        position: absolute;
        margin: auto;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 99999;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #FFF;
    }
    .loader {
        flex-shrink: 0;
        width: 150px;
        height: 150px;
        border-radius: 50%;
        border: 3px solid transparent;
        border-top-color: #16a085;
        animation: spin 1.7s linear infinite;
        z-index: 11;
        
        &:before {
            content: "";
            position: absolute;
            top: 5px;
            left: 5px;
            right: 5px;
            bottom: 5px;
            border-radius: 50%;
            border: 3px solid transparent;
            border-top-color: #e74c3c;
            animation: spin-reverse .6s linear infinite;
        }
        
        &:after {
            content: "";
            position: absolute;
            top: 15px;
            left: 15px;
            right: 15px;
            bottom: 15px;
            border-radius: 50%;
            border: 3px solid transparent;
            border-top-color: #f9c922;
            animation: spin 1s linear infinite;
        }
    }
    
    .animation-message {
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        padding: 10px 20px;
        border-radius: 4px;
        z-index: 10000;
        font-weight: bold;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        
        &.success {
            background-color: #f0f9eb;
            color: #67c23a;
            border: 1px solid #e1f3d8;
        }
        
        &.error {
            background-color: #fef0f0;
            color: #f56c6c;
            border: 1px solid #fde2e2;
        }
    }
}
</style>